<template>
  <PageContainer>
    <view class="container">
      <Header title="填写表单" :is-box-shadow="false" />
      <view class="header-box mb-16">
        <view class="form-title">{{ detailRef.title }}</view>
        <view class="form-desc">{{ detailRef.details }}</view>
        <view v-if="detailRef.endTime" class="fz-12">填写截止：{{ detailRef.endTime }}</view>
      </view>
      <view style="background-color: #fff">
        <BasicsForm :schemas="schemas" @register="register" @submit="onSubmit" />
      </view>
    </view>
    <ChoseRole ref="choseRoleRef" @ok="handleChoseRoleOk"></ChoseRole>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* serviceFormFilling 填写表单 */
  import {
    addServiceTicketFormDto,
    serviceTicketFormFillTemplateDetail,
    serviceTicketFormRecordDetail,
  } from '@/api/serviceForm';
  import type {
    ServiceTicketFormDetailResult,
    ServiceTicketFormSnapshootDetailResult,
    UserRoleVoList,
  } from '@/api/serviceForm/types';
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import { onLoad, redirectTo } from '@/router';
  import { ref, unref, reactive } from 'vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormSchema } from '@/components/Form';
  import { forEach, isArray } from 'lodash-es';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { PermissionsTypeEnum } from '@/enums/serviceFormEnum';
  import ChoseRole from './components/ChoseRole.vue';

  const schemas = ref<FormSchema[]>([]);
  const [register, {}] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'bind',
    btnGroupOptions: {
      styles: {
        backgroundColor: '#fff',
      },
      submit: {
        text: '提交',
        customStyle: {
          backgroundColor: '#2878FF',
          color: '#fff',
        },
      },
    },
  });

  const serviceTicketFormId = ref<number>();
  const serviceTicketRecordId = ref<number>();
  const detailRef = reactive({
    title: '',
    details: '',
    endTime: '',
    serviceTicketFormId: 0,
    roleId: void 0 as PermissionsTypeEnum | undefined,
    userRoleVoList: null as UserRoleVoList[] | null,
  });

  // 设置表单填写权限
  const choseRoleRef = ref<InstanceType<typeof ChoseRole>>();
  const isShowChoseRole = (
    role: PermissionsTypeEnum | undefined,
    resData: ServiceTicketFormDetailResult,
  ) => {
    if (role !== void 0) {
      detailRef.roleId = role;
      return;
    }
    const userRoleVoList = resData.userRoleVoList;
    if (!userRoleVoList?.length) {
      return;
    }
    if (userRoleVoList?.length === 1) {
      detailRef.roleId = userRoleVoList[0].id;
      return;
    }

    choseRoleRef?.value?.openShow(userRoleVoList);
  };
  const handleChoseRoleOk = (roleId: number) => {
    detailRef.roleId = roleId;
  };
  onLoad<'serviceFormFilling'>(async (op) => {
    serviceTicketFormId.value = op.serviceTicketFormId;
    serviceTicketRecordId.value = op.serviceTicketRecordId;
    const list: FormSchema[] = [];
    let resData: ServiceTicketFormSnapshootDetailResult | ServiceTicketFormDetailResult;

    if (op.serviceTicketRecordId) {
      resData = await serviceTicketFormRecordDetail(op.serviceTicketRecordId);
    } else {
      resData = await serviceTicketFormFillTemplateDetail(op.serviceTicketFormId);
      isShowChoseRole(op.role, resData);
    }

    detailRef.title = resData.title;
    detailRef.details = resData.details;
    detailRef.endTime = resData.endTime;
    detailRef.serviceTicketFormId = op.serviceTicketFormId;
    forEach(resData.formItemList, (v) => {
      const answer = v.formUserItemAnswerList;
      const defaultValue = isArray(answer) ? answer[answer.length - 1].content : '';
      list.push({
        field: v.id.toString(),
        label: v.showName,
        component: v.itemType,
        required: !!v.isRequired,
        defaultValue,
        rules: [
          {
            required: !!v.isRequired,
            errorMessage: v.value,
          },
        ],
        componentProps: {
          placeholder: v.value,
          limit: v.itemType === 'UploadImg' ? 9 : void 0,
          localdata: localDataMapping(v.customFormItemAnswerList || [], {
            label: 'words',
            value: 'id',
          }),
        },
      });
    });
    schemas.value = [...list];
  });

  const isRequest = ref(false);
  const onSubmit = (vals: Recordable) => {
    if (unref(isRequest)) return;
    isRequest.value = true;
    const answerList: any[] = [];
    for (const key in vals) {
      let content = vals[key];
      if (!isArray(content)) content = content.toString().split(',');
      const answerItem = {
        formItemId: key,
        content,
      };
      answerList.push(answerItem);
    }

    addServiceTicketFormDto({
      serviceTicketFormId: detailRef?.serviceTicketFormId,
      serviceTicketRecordId: serviceTicketRecordId.value,
      roleId: detailRef.roleId,
      customFormItem: {
        customFormId: detailRef?.serviceTicketFormId as number,
        answerList: answerList,
      },
    })
      .then(({ id }) => {
        redirectTo({
          name: 'serviceFormFillingResult',
          options: {
            id,
          },
        });
      })
      .catch(() => (isRequest.value = false));
  };
</script>

<style lang="scss" scoped>
  .container {
    .header-box {
      height: fit-content;
      padding: 32rpx;
      display: flex;
      flex-direction: column;
      gap: 24rpx;
      color: #666664;
      background-color: #fff;
      .form-title {
        font-size: 32rpx;
        line-height: 48rpx;
        font-weight: bolder;
        color: #333;
        word-break: break-all;
      }
      .form-desc {
        font-size: 28rpx;
        line-height: 40rpx;
        white-space: pre-wrap;
      }
    }
  }
</style>
